package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.WemediaFeign;
import com.heima.feigns.ArticleFeign;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.dto.PageResponseResult;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserRealname;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {


    @Override
    public ResponseResult listByStatus(AuthDTO dto) {
        // 检查参数
        dto.checkParam();
        //封装查询条件
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        //封装分页条件
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        //执行查询得到的分页数据
        IPage<ApUserRealname> result = this.page(page, wrapper);
        return new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal(), result.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;



    /**
     * @param dto    id ： realnameId   msg ： 驳回原因
     * @param status 2 审核失败   9 审核成功
     * @return
     */
   // @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 200000)
    @Override  // 用户服务-认证审核用户功能实现
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        // 校验参数  id不为空
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id不能为空");
        }
        //根据id查询实名认证信息
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (apUserRealname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的实名认证信息不存在");
        }
        //判断认证状态是否待审核
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "实名认证状态,不是待审核状态");
        }
        //查询认证信息所关联的apUser账户
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的ap用户信息不存在");
        }
        //修改实名认证状态  (补全  时间  状态  原因)
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        this.updateById(apUserRealname);
        //判断状态是否为9
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //TODO: 开通自媒体账户
            WmUser wmUser = createWmUser(apUser);
            //TODO: 创建作者信息
            createAuthor(wmUser);
        }
        // TODO 制造异常 查看是否回滚
       // System.out.println(1/0);

        return ResponseResult.okResult();
    }

    /**
     * 远程创建作者信息
     * @param wmUser
     */
    @Autowired
    ArticleFeign articleFeign;
    private void createAuthor(WmUser wmUser) {
        //  使用feign远程查询对应的作者信息是否存在
        ResponseResult<ApAuthor> authorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if(!authorResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApAuthor apAuthor = authorResult.getData();
        // 如果不存在  创建作者信息
        if(apAuthor!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "作者信息存在");
        }
        apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());

        // 使用feign远程保存作者信息
        ResponseResult saveResult = articleFeign.save(apAuthor);
        if(!saveResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }

    /**
     * 远程调用自媒体服务   开通自媒体账户
     *
     * @param apUser 基于app 账户创建
     * @return
     */
    @Autowired
    WemediaFeign wemediaFeign;
    private WmUser createWmUser(ApUser apUser) {
        // 远程查询  自媒体账户是否已经存在
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        if (wmUser != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "自媒体账户已经存在");
        }
        //  如果不存在  创建自媒体账户
        wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setApUserId(apUser.getId());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
       /*
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());*/

        // 远程保存自媒体账户信息
        ResponseResult<WmUser> save = wemediaFeign.save(wmUser);
        if(!save.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return save.getData(); //  返回保存成功的自媒体用户信息
    }


}